<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/db/mysql.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/class/model.php';

class user {
    
    public $id;
    public $name;
    public $surname;
    public $email;
    
    public $sql;
    
    function __construct() {
        $conf = model::configuredb();
        $this->sql = new sql_db($conf->dbhost,$conf->dbuser,$conf->dbpasswd,$conf->dbmain);
        if (!$this->sql->db_connect_id) $this->dbErr = true;
    }
    
    function checkUserLogin($login,$passwd) {
        // проверяем связку логин - пароль. авторизуем ? id : false
        $query =  "select `id`, `name`, `email` from `user` where `email`='".$login."' and `passwd`='".md5($passwd)."'";
        if (!$this->sql->sql_query($query)) {            
            $this->dbErr = $this->sql->sql_error();
            return false;
        }
        if ($this->sql->sql_numrows() != 1) return false;
     
        $row = $this->sql->sql_fetchrow();
        $this->id = $row['id'];
        $this->name = $row['name'];
        $this->email = $row['email'];
        
        ini_set('session.gc_maxlifetime', 3600*60);
        ini_set('session.cookie_lifetime', 3600*60);

        setcookie('usid',$row['id'],time()+3600*30,"/");

        if (session_id()) {
            $query = "update `user` set `sid` = '".session_id()."' where `id` = '".$row['id']."'";
            if (!$this->sql->sql_query($query)) {
                $this->dbErr = $this->sql->sql_error();
                return false;
            }
        }
        return $row['id'];
    }
    
    function checkUserAuth() {
        //проверяем наличее сессии: id или false
        $query = "select `id`,`name`,`email` from `user` where `sid` = '".session_id()."'";
        if (!$this->sql->sql_query($query)) {            
            $this->dbErr = $this->sql->sql_error();
            return 0;
        }
        if ($this->sql->sql_numrows() !== 1) return false;
        
        $row = $this->sql->sql_fetchrow();
        
        $this->id = $row['id'];
        $this->name = $row['name'];
        $this->email = $row['email'];
        
        return $row['id'];
    }
    
    function exitUser() {
        $query = "update `user` set `sid`='' where `sid`='".session_id()."'";
        if (!$this->sql->sql_query($query)) {            
            $this->dbErr = $this->sql->sql_error();
            return false;
        }
        
        setcookie('PHPSESSID','',time(),"/");
        unset ($_COOKIE['PHPSESSID']);
        session_destroy();
        echo '1';
    }
}
?>
